﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WiseLinkWPF.Windows.Controls.GridView;
using CCF20Model;
using WiseLinkWPF.Windows.Controls;
using WiseLinkWPF.Windows.Data;
namespace CCF20
{
    /// <summary>
    /// Interaction logic for InStock.xaml
    /// </summary>
    public partial class InStock : UserControl
    {
        DeviceModel dm;
        CustomerModel cm;
        VehicleMaintenanceRecordModel vrm;
        private CollectionViewSource CustomerLookupView;
        private int? CurrentVehicleID;
        public InStock()
        {
            
            InitializeComponent();


            dm = new DeviceModel();
            cm = new CustomerModel();
            vrm = new VehicleMaintenanceRecordModel();
            this.radGridView1.ItemsSource = dm.GetDevice();
            

        }

        private void radGridView1_AddingNewDataItem(object sender, WiseLinkWPF.Windows.Controls.GridView.GridViewAddingNewEventArgs e)
        {
            e.NewObject = new Device();
        }

        private void radGridView1_RowEditEnded(object sender, WiseLinkWPF.Windows.Controls.GridViewRowEditEndedEventArgs e)
        {
            if (e.EditAction == GridViewEditAction.Cancel)
            {
                return;
            }
            if (e.EditOperationType == GridViewEditOperationType.Insert)
            {
                //Add the new entry to the data base.
                Device newDevice = e.NewData as Device;
                newDevice.DeviceStatus = "库存";
                dm.Insert(newDevice,true);
            }
            else if (e.EditOperationType == GridViewEditOperationType.Edit)
            {
                dm.Update(e.EditedItem as Device);
            }
            this.Dispatcher.BeginInvoke(new Action(() => this.radGridView1.Rebind()));

            //this.radGridView1.Rebind();
            this.radGridView1.ShowInsertRow = false;
        }

        private void Instock_Add_Click(object sender, RoutedEventArgs e)
        {
            string strAction = ((Button)sender).Content.ToString();
            string strUpdatedField = string.Empty;           
            string strUpdatedValue = string.Empty;           
            switch (strAction)
            {
                case "手动入库":
                    this.radGridView1.BeginInsert();
                    return;
                case "售出":
                    SimpleCustomerInfo sci = (SimpleCustomerInfo)this.CustomerLookupComboBox.SelectedValue;
                    if (sci == null)
                    {
                        MessageBox.Show("请先选择客户", "CCF2.0", MessageBoxButton.OK);
                        return;
                    }

                    strUpdatedField = "Customer";
                    strUpdatedValue = sci.ID.ToString();
                    break;
                case "归库":
                    strUpdatedField = "DeviceStatus";
                    strUpdatedValue = "库存";
                    break;
                
                case "发货入库":
                    strUpdatedField = "DeviceStatus";
                    strUpdatedValue = "在途";
                    break;
                case "到货入库":
                    strUpdatedField = "DeviceStatus";
                    strUpdatedValue = "库存";
                    break;
                case "到货索赔":
                    strUpdatedField = "DeviceStatus";
                    strUpdatedValue = "索赔";
                    break;
                case "注册IDC":
                    strUpdatedField = "isRegistered";
                    break;
                case "特殊IDC":
                    strUpdatedField = "isSpecialIDC";
                    break;
                case "打印":
                    MyPrint myPrint = new MyPrint();
                    myPrint.MySource = this.radGridView1;
                    myPrint.PrintPreview();
                    myPrint.Show();
                    
                    return;
                case "列选项":
                    ChoseColumn myColumn = new ChoseColumn(null,this.radGridView1,"Device");
                    myColumn.ShowDialog();
                    return;
                    

            }
            UpdateDeviceStatus(strUpdatedField, strUpdatedValue);
        }

        private void UpdateDeviceStatus(string strUpdateField, string strUpdateValue)
        {
            if (this.radGridView1.SelectedItems.Count < 1)
            {
                MessageBox.Show("请先选中表格中的数据", "CCF2.0", MessageBoxButton.OK);
                return;
            }
            foreach (var item in this.radGridView1.SelectedItems)
            {
                var updatedItem = item as Device;
                if ((updatedItem == null) || (updatedItem.DeviceStatus == null))
                {
                    continue;
                }

                if (strUpdateField.Equals("isRegistered")&&(updatedItem.isRegistered))
                {
                    strUpdateField = "UnRegister";
                }

                if (strUpdateField.Equals("isSpecialIDC")&&(updatedItem.isSpecialIDC))
                {
                    strUpdateField = "UnSpecialIDC";
                }
                switch (strUpdateField)
                {
                    case "Customer":
                        if (updatedItem.DeviceStatus.Equals("售出"))
                        {
                            MessageBox.Show(string.Format("设备已售出给客户:{0}，请先归库",updatedItem.CustomerName), "CCF2.0", MessageBoxButton.OK);
                            return;
                        }
                        updatedItem.CustomerID = Convert.ToInt32(strUpdateValue);
                        updatedItem.DeviceStatus = "售出";
                        updatedItem.SaleDate = DateTime.Now;
                        break;
                    case "DeviceStatus":
                        
                        if (strUpdateValue.Equals("库存"))
                        {
                            if (updatedItem.isRegistered)
                            {
                                MessageBox.Show("设备处于注册状态，不可以归库", "CCF2.0", MessageBoxButton.OK);
                                return;
                            }
                            updatedItem.DeviceStatus = strUpdateValue;
                            updatedItem.InStockDate = DateTime.Now;
                            // Also need to remove customer association in the Model
                            // remove the vehicle association
                            // Remove Maintenance association
                        }
                        break;
                    case "isRegistered":
                        if (!updatedItem.DeviceStatus.Equals("售出"))
                        {
                            MessageBox.Show("设备未售出，不可以注册", "CCF2.0", MessageBoxButton.OK);
                            return;
                        }
                        updatedItem.isRegistered = true;
                        break;
                    case "UnRegister":
                       
                            MessageBoxResult confirmResult = MessageBox.Show(
                                string.Format("请确认取消注册选中的{0}个设备", radGridView1.SelectedItems.Count), "CCF2.0", MessageBoxButton.OKCancel);

                            if (confirmResult != MessageBoxResult.OK)
                            {
                                return;
                            }
                            updatedItem.isRegistered = false;
                            updatedItem.isSpecialIDC = false;
                        
                        break;
                    case "isSpecialIDC":

                        // Before you register a special IDC, you need to register first.
                        if (!updatedItem.isRegistered)
                        {
                            
                            MessageBox.Show(
                                string.Format("IDC{0} 还未注册", updatedItem.DeviceIDCNo), "CCF2.0", MessageBoxButton.OK);
                            return;
                        }
                        updatedItem.isSpecialIDC = true;
                        break;
                    case "UnSpecialIDC":
                        
                        updatedItem.isSpecialIDC = false;
                        break;
                }
                dm.Update(updatedItem);
            }
            this.Dispatcher.BeginInvoke(new Action(() => this.radGridView1.Rebind()));
            //this.radGridView1.Rebind();
        }
        private void Instock_Delete_Click(object sender, RoutedEventArgs e)
        {
            int selectionCount = this.radGridView1.SelectedItems.Count;
            if (selectionCount == 0)
            {
                MessageBox.Show("请先选中表格中的数据", "CCF2.0", MessageBoxButton.OK);
                return;
            }
            foreach (var item in this.radGridView1.SelectedItems)
            {
                var removedItem = item as Device;
                if ((removedItem == null) || (removedItem.DeviceStatus == null))
                {
                    continue;
                }
                if (removedItem.DeviceStatus.Equals("售出"))
                {
                    MessageBox.Show("设备已售出，不可以删除", "CCF2.0", MessageBoxButton.OK);
                    return;
                }
            }
            MessageBoxResult confirmResult = MessageBox.Show(string.Format("请确认删除表格中的{0}条数据",selectionCount), "CCF2.0", MessageBoxButton.OKCancel);

            if (confirmResult != MessageBoxResult.OK)
            {
                return;
            }

            foreach (var item in this.radGridView1.SelectedItems)
            {
                var removedItem = item as Device;
                dm.Delete(removedItem.DeviceID);
            }
            this.Dispatcher.BeginInvoke(new Action(() => this.radGridView1.Rebind()));
            //this.radGridView1.Rebind();
        }

        private void radGridView1_SelectionChanged(object sender, WiseLinkWPF.Windows.Controls.SelectionChangeEventArgs e)
        {
            if (e.AddedItems.FirstOrDefault() != null)
            {
                this.radGridView1.CurrentItem = e.AddedItems.First();
                ShowMaintenanceRecord();
               
            }
        }
        private void ShowMaintenanceRecord()
        {
            Device deviceData = this.radGridView1.CurrentItem as Device;
            if ((deviceData != null) && (deviceData.VehicleID !=null))
            {
                this.radMaintenanceRecord.ItemsSource = vrm.GetVehicleMaintenanceRecord(deviceData.VehicleID);
                CurrentVehicleID = deviceData.VehicleID;
            }
            else
            {
                this.radMaintenanceRecord.ItemsSource = null;
            }
            this.radMaintenanceRecord.Rebind();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            CustomerLookupView = (CollectionViewSource)this.FindResource("CustomerLookup");
            cm.GetSimpleCustomerInfo();
            CustomerLookupView.Source = cm.MySimpleCustomerInfo;

            ShowMaintenanceRecord();
            //this.CustomerLookupComboBox.ItemsSource = cm.GetSimpleCustomerInfo().ToList();
        }

        private void radMaintenanceRecord_RowEditEnded(object sender, GridViewRowEditEndedEventArgs e)
        {
            if (e.EditAction == GridViewEditAction.Cancel)
            {
                return;
            }
            else if (e.EditOperationType == GridViewEditOperationType.Edit)
            {
                MaintenanceTypeData mtd = e.EditedItem as MaintenanceTypeData;
                if (mtd != null)
                {
                    vrm.SetupVehicleMaintenanceRecord(CurrentVehicleID, mtd.MaintenanceTypeID, mtd.LastServiceMileage,mtd.LastServiceDate, mtd.IsChoosen);
                }
            }
            this.radMaintenanceRecord.Rebind();
            this.radMaintenanceRecord.ShowInsertRow = false;
        }

        private void ApplyServiceDateMileage_Click(object sender, RoutedEventArgs e)
        {
            int? Mileage = Convert.ToInt32(this.LastServiceMileage.Value);
            DateTime? ServiceDate = this.LastServiceDate.SelectedDate;

            if ((Mileage == null) || (ServiceDate == null))
            {
                MessageBox.Show("最新服务里程和最新服务时间不可为空", "CCF 2.0", MessageBoxButton.OK);
                return;
            }

            // Get only players with a number less than 10  15: 
            
            ColumnFilterDescriptor numberColumnFilter =  new ColumnFilterDescriptor((IDataFieldDescriptor)this.radMaintenanceRecord.Columns["IsChoosen"]);
            numberColumnFilter.FieldFilter.Filter1.Operator = FilterOperator.IsEqualTo;
            numberColumnFilter.FieldFilter.Filter1.Value = true;
            this.radMaintenanceRecord.FilterDescriptors.Add(numberColumnFilter);
            this.radMaintenanceRecord.Rebind();
            
            foreach (var r in radMaintenanceRecord.Items)
            {
                MaintenanceTypeData mtd = r as MaintenanceTypeData;
                if (mtd != null)
                {
                    vrm.UpdateVehicleMaintenanceRecord(mtd.MaintenanceTypeID, Mileage, ServiceDate);
                }
            }
            radMaintenanceRecord.Rebind();

        }

        private void radGridView1_CellValidating(object sender, GridViewCellValidatingEventArgs e)
        {
            // if there is no change of the value, no need to validate.
            if (e.NewValue == e.OldValue)
                return;
            GridViewCell cell = e.Cell;
            string searchValue = e.NewValue as string;
            // If the input is datetime, it won't convert as string.
            if (string.IsNullOrEmpty(searchValue))
                return;

            string validationText = string.Empty;
            switch (cell.Column.UniqueName)
            {
                case "DeviceIDCNo":
                    if (dm.IsDuplicateDevice(searchValue, "IDCSimNum"))
                    {
                        validationText="重复的设备SIM卡号";
                    }
                    break;
                case "DeviceKey":
                    if (dm.IsDuplicateDevice(searchValue, "DeviceKey"))
                    {
                        validationText="重复的设备序列号";
                    }
                    break;
                default:
                    break;
            }
            if (!string.IsNullOrEmpty(validationText))
            {
                ToolTipService.SetToolTip(cell, validationText);
                e.IsValid = false;
                e.ErrorMessage = validationText;

            }

        }

        private List<Device> PagedData()
        {
            List<Device> printData = this.radDataPager1.Source.OfType<Device>().ToList();
            return printData;
        }

    }
}
